package cn.com.connected.base.aop;

import cn.com.connected.base.exception.ErrorCode;
import cn.com.connected.base.params.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 注意：只支持 @ResponseBody  如果是RestController默认带了ResponseBody
 * 拦截Controller方法默认返回参数，统一处理返回值/响应体
 * 注意 必须得加 basePackages 否则会影响 swagger 的返回值
 */
@Slf4j
@ControllerAdvice(basePackages = {"cn.com.connected.controller"},assignableTypes = {RestController.class})
public class AdviceResponseBody implements ResponseBodyAdvice {

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        JsonResult result = null;

        if (o instanceof JsonResult){
            result = (JsonResult) o;
        }else{
            result = new JsonResult(o, ErrorCode.SYSTEM_SUCCESS);
        }

        return result;
    }


    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }
}
